package com.guosheng.service.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class CacheSingleService implements ICacheService {

    @Autowired
    private JedisPool jedisPool;

    public String set(String key, String value) {
        Jedis jedis = null;
        jedis = getResource();
        return jedis.set(key,value);
    }

    public Long incrBy(String key, long increment) {
        Long i = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            i = jedis.incrBy(key,increment);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnResource(jedis);
        }
        return i;
    }

    private Jedis getResource(){
        return jedisPool.getResource();
    }

    private void returnResource(Jedis jedis){
        if(jedis != null) jedis.close();
    }

    public String get(String key) {
        try {
            Jedis jedis = getResource();
            return jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
